package com.study.zzedu.ui.schoolroll.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.study.zzedu.ui.exercise.activity.IntroduceItemActivity;
import com.study.zzedu.utils.Utils;
import com.study.zzedu.widget.TreeViewAdapter;
import com.study.zzedu.widget.bean.LayoutItem;
import com.study.zzedu.widget.bean.TreeNode;
import com.study.zzedu.widget.bean.TreeViewBinder;
import com.study.zzedu.R;
import com.study.zzedu.bean.BranchNode;
import com.study.zzedu.bean.HeadNodeGrade;
import com.study.zzedu.bean.HeadViewBinder;
import com.study.zzedu.bean.LeafGradeViewBinder;
import com.study.zzedu.bean.LeafNode;
import com.study.zzedu.bean.LeafNodeGrade;
import com.study.zzedu.bean.RootGradeViewBinder;
import com.study.zzedu.bean.RootNode;
import com.study.zzedu.bean.RootNodeGrade;
import com.study.zzedu.ui.discussdetail.DiscussDetailActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.study.zzedu.ui.schoolroll.SchoolRollActivity.gardeInfo;

/**
 *
 */

public class GradeFragment extends Fragment {

    private List<TreeNode> list = new ArrayList<>();
    RecyclerView mRecyclerView;

    private TreeViewAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_grade, container, false);
        initView(rootView);
        return rootView;
    }

    private String termRemain = "";
    private int termIndex = 1;

    protected void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_list_data);
        LinearLayoutManager lm = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(lm);
        try {
            if (gardeInfo == null)
                return;
            //第一层循环
            for (int i = 0; i < gardeInfo.length(); i++) {
                JSONObject job1 = gardeInfo.getJSONObject(i);
                try {
                    if (!termRemain.equals("("+job1.getString("term")+")")) {
                        termRemain = "("+job1.getString("term")+")";
                        TreeNode headNode = new TreeNode<>(new HeadNodeGrade(termRemain, String.valueOf(termIndex++)));
                        list.add(headNode);
                    }
                    TreeNode rootNode = new TreeNode<>(new RootNodeGrade(Utils.getDefaultStringValue(job1,"course"), Utils.getDefaultStringValue(job1,"totalScore")));

                    TreeNode<LeafNodeGrade> leafNode = new TreeNode<>(new LeafNodeGrade(Utils.getDefaultStringValue(job1,"learnScore"),Utils.getDefaultStringValue(job1,"testScore") , Utils.getDefaultStringValue(job1,"examScore"), Utils.getDefaultStringValue(job1,"over")));
                    rootNode.addChild(leafNode);

                    list.add(rootNode);
                } catch (Exception e) {
                    e.toString();
                }
            }
            if (gardeInfo.length() > 0) {
                view.findViewById(R.id.rl_default_grade).setVisibility(View.GONE);
                initAdapter();
            } else {
                return;
            }

        } catch (Exception e) {
            LogUtil.e("Exception", getActivity() + " " + e.toString());
            e.toString();
        }

    }

    private void initAdapter() {
        adapter = new TreeViewAdapter(list, Arrays.asList(new HeadViewBinder(), new RootGradeViewBinder(), new LeafGradeViewBinder())) {

            @Override
            public void toggleClick(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {
                if (isOpen) {
                    addNewNode(treeNode);
                } else {
                    adapter.lastToggleClickToggle();
                }
            }

            @Override
            public void toggled(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {
                viewHolder.findViewById(R.id.ivNode).setRotation(isOpen ? 90 : 0);
            }

            @Override
            public void checked(TreeViewBinder.ViewHolder viewHolder, View view, boolean checked, TreeNode treeNode) {

            }

            @Override
            public void itemClick(TreeViewBinder.ViewHolder viewHolder, View view, TreeNode treeNode) {
                String name = null;
                LayoutItem item = treeNode.getValue();
                if (item instanceof RootNode) {
                    name = ((RootNode) item).getName();
                } else if (item instanceof BranchNode) {
                    name = ((BranchNode) item).getName();
                } else if (item instanceof LeafNode) {
                    name = ((LeafNode) item).getName();
                    switch (((LeafNode) item).getDataType()) {
                        case "讨论":
                            AppConstant.contentID = ((LeafNode) item).getContentCode();
                            startActivity(new Intent(view.getContext(), DiscussDetailActivity.class));
                            break;
                        case "测试":
                            AppConstant.chapterCode = ((LeafNode) item).getContentCode();
                            Intent intent = new Intent(getContext(), IntroduceItemActivity.class);
                            startActivity(intent);
                            break;
                        case "视频":
                            AppConstant.contentCode = ((LeafNode) item).getContentCode();
//                            if(longVideoBean != null){
//                                longVideoBean.setTitle(((LeafNode) item).getName());
//                                longVideoBean.setWatchDuration(((LeafNode) item).getLastPosition());
//                            }
//                            getPresenter().getVideoURL(getContext(),((LeafNode) item).getUrl());
                            break;
                    }
                }
                //Toast.makeText(MainActivity34.this, name, Toast.LENGTH_SHORT).show();
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(adapter);
    }

    private void addNewNode(final TreeNode treeNode) {
        //autoProgress(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                String name = null;
                LayoutItem item = treeNode.getValue();
                if (item instanceof RootNode) {
                    name = ((RootNode) item).getName();
                } else if (item instanceof BranchNode) {
                    name = ((BranchNode) item).getName();
                } else if (item instanceof LeafNode) {
                    name = ((LeafNode) item).getName();
                }

                List<TreeNode> list = treeNode.getChildNodes();
                boolean hasLeaf = false;
                for (TreeNode child : list) {
                    if (child.getValue() instanceof LeafNode) {
                        hasLeaf = true;
                        break;
                    }
                }
                if (!hasLeaf) {
//                    TreeNode<LeafNode> leafNode1 = new TreeNode<>(new LeafNode(name+"新增叶1"));
//                    TreeNode<LeafNode> leafNode2 = new TreeNode<>(new LeafNode(name+"新增叶2"));
//                    treeNode.addChild(leafNode1);
//                    treeNode.addChild(leafNode2);
                }
                autoProgress(false);
                adapter.lastToggleClickToggle();
            }
        }, 200);
    }

    private ProgressDialog progressDialog;

    private void autoProgress(boolean show) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("正在加载数据。。。");
        }
        if (show) {
            progressDialog.show();
        } else {
            progressDialog.dismiss();
        }
    }
}
